package com.leo.boot.jpa.search;

import org.apache.commons.lang3.StringUtils;

import java.util.StringJoiner;

public class ExpressionUtils {

    public static String print(Expression expression) {
        if (expression == null || expression == Expression.EMPTY) {
            return StringUtils.EMPTY;
        }
        StringJoiner sj = new StringJoiner(System.lineSeparator());
        add(expression, sj, 0);
        return sj.toString();
    }

    private static void add(Expression expression, StringJoiner sj, int depth) {
        if (expression.getOperator().isConditional()) {
            String content = "'" + expression.getOperator().getOp() + "':";
            if (depth != 0) {
                content = "- " + content;
            }
            sj.add(StringUtils.leftPad(content, content.length() + depth * 2));
            add((Expression) expression.getLeft(), sj, depth + 1);
            add((Expression) expression.getRight(), sj, depth + 1);
        } else {
            String content = "- " + expression;
            sj.add(StringUtils.leftPad(content, content.length() + depth * 2));
        }
    }
}
